<template>
  <div class="upload-container">
    <el-button size="mini"
               @click="openUploadDialog">上传媒体
    </el-button>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <el-button size="small" type="primary" id="btn-video-select">点击上传</el-button>
      <el-button size="small" type="success" @click="uploader.start()">上传到服务器</el-button>
      <div class="el-upload__tip">注意：上传组件初始化会有一定延迟；只能上传mp4/mp3文件，且不能超过20M。</div>
      <template>
        <ul class="el-upload-list el-upload-list--picture">
          <li tabindex="0" class="el-upload-list__item is-success" v-for="v in fileList">
            <a class="el-upload-list__item-name"><i class="el-icon-document"></i>
              {{v.saveFileName || v.fileName}}
              <el-progress :percentage="v.percent"></el-progress>
              <!--<div>上传进度{{v.percent}}%</div>-->
            </a>
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check"></i>
            </label>
            <i class="el-icon-close" @click="removeFile(v.fileId)"></i>
          </li>
        </ul>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import plupload from "plupload";
import request from "../../../utils/request";

const MODULE_FLAG = "0";
const SERVICE_FLAG = "article_editor";

let times = 10;

export default {
  name: 'EditorVideoUpload',
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      uploader: null,
    }
  },
  mounted: function() {
  },
  methods: {
    openUploadDialog() {
      if (!this.uploader) {
        this.lazyInitUploader();
      }
      this.fileList.length = 0;
      this.dialogVisible = true;
    },
    checkAllSuccess() {
      this.fileList.map(v => {
        if (!v.saveFileName)
          return false;
      });
      return true;
    },
    handleSubmit() {
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有媒体上传成功 或 出现了网络问题，请刷新页面重新上传！');
        return
      }

      let arr = [];
      this.fileList.map(v => {
        if (v.showUrl)
          arr.push({'url': v.showUrl});
      });
      this.$emit('successCBKas', arr);
      this.fileList = [];
      this.dialogVisible = false
    },
    removeFile(fileId) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].fileId === fileId) {
          this.fileList.splice(i, 1);
          return;
        }
      }
    },
    lazyInitUploader() {
      if (document.getElementById('btn-video-select')) {
        times = 10;
        this.initUploader();
      } else {
        if (times > 0) {
          let _this = this;
          setTimeout(function () {
            _this.lazyInitUploader();
            times --;
          }, 100);
        }
      }
    },
    initUploader() {
      const loading = this.$loading({
        lock: true,
        text: '正在加载上传组件配置',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      });
      let _this = this;
      let opt = {}, dir = '', saveFileName = '';
      let uploader = new plupload.Uploader({
        runtimes : 'html5,flash,silverlight,html4',
        browse_button : 'btn-video-select',
        multi_selection: true,
        // container: 'dialog',
        flash_swf_url : '../lib/Moxie.swf',
        silverlight_xap_url : '../lib/Moxie.xap',
        url : 'http://oss.aliyuncs.com',

        filters: {
          mime_types : [ //只允许上传图片和zip文件
            { title : "Image files", extensions : "mp4,mp3" }
          ],
          max_file_size : '20mb', //最大只能上传10mb的文件
          prevent_duplicates : false //不允许选取重复文件
        },

        init: {

          PostInit: function () {
            _this.uploader = uploader;

            request({
              url: '/system/attachment/signature/' + MODULE_FLAG + '/' + SERVICE_FLAG
            }).then(resp => {
              if (resp.code === 200) {
                let data = resp.data;
                opt = {
                  'url': data.host,
                  'multipart_params': {
                    'key': data.dir + "/",
                    'policy': data.policy,
                    'OSSAccessKeyId': data.accessid,
                    'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                    'callback': data.callback,
                    'signature': data.signature,
                  }
                };
                dir = data.dir + '/';

                loading.close();
              }
            });
          },

          FilesAdded: function (up, files) {
            let fileId = '';
            plupload.each(files, function (file) {
              fileId = file.id;
              let orginFileName = file.name;
              let lastIndex = orginFileName.lastIndexOf(".");
              let ext = orginFileName.substring(lastIndex + 1, orginFileName.length);
              saveFileName = file.id+"."+ext;
              _this.fileList.push({
                fileName: orginFileName,
                tmpSaveFileName: saveFileName,
                percent: 0,
                fileId: fileId,
              });
            });
          },

          BeforeUpload: function(up, file) {
            _this.fileList.map(v => {
              if (v.fileId === file.id) {
                opt.multipart_params.key = dir + v.tmpSaveFileName;
                uploader.setOption(opt);
              }
                uploader.setOption(v.option);
            })
          },

          UploadProgress: function (up, file) {
            _this.fileList.map(v => {
              if (v.fileId === file.id)
                v.percent = file.percent;
            })
          },

          FileUploaded: function (up, file, resp) {
            let res = JSON.parse(resp.response);
            _this.fileList.map(v => {
              if (v.fileId === file.id) {
                v['saveFileName'] = res.data.saveFileName;
                v['showUrl'] = res.data.showUrl;
                v.tmpSaveFileName = null;
              }
            });
          },

          UploadComplete: function(up, files) {
            _this.uploader = null;
            try {
              up.destroy();
            } catch (e) {
            }
          },

          Error: function (up, err) {
            loading.close();
            _this.$message(err.message);
            console.log('组件上传文件err:', err);
          },

          Destroy: function (up) {
            loading.close();
          }
        }
      });
      uploader.init();
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
.el-upload-list--picture .el-upload-list__item {
  padding-left: 10px;
  /deep/ .is-success .el-upload-list__item-name {
    line-height: 2em;
  }
}
</style>
